<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <!-- <el-input v-model="listQuery.userId" clearable class="filter-item" style="width: 200px;" :placeholder="$t('Please_enter_member_ID')"/> -->
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;" :placeholder='$t("请输入收货人名称")'/>

      <el-cascader
        :placeholder="$t('请选择区域地址')"
        class="filter-item"
        v-model="listQuery.regionIds"
        :options="countrys"
        @active-item-change="handleItemChange"
        :props="props"
        clearable
        filterable
      ></el-cascader>

      <el-button class="filter-item" type="info" icon="el-icon-search" @click="handleFilter">{{$t('Search')}}</el-button>
<!--      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">{{$t('Find')}}</el-button>-->
    </div>
<!--    <div class="app-container">
      <el-switch
        style="display: block"
        v-model="listQuery.openFilter"
        active-color="#13ce66"
        inactive-color="#ff4949"
        :active-text="$t('唯一用户开启')"
        :inactive-text="$t('唯一用户关闭')"
        @change="openEvent()"
        >
      </el-switch>
    </div>-->

    <!-- 查询结果 -->
    <el-table
      :header-cell-style="{background:'#2f333a',color:'#ffffff',top:'5px','font-size':'15px'}"
      v-loading="listLoading" :data="list" :element-loading-text="$t('Searching')" border fit highlight-current-row>
      <el-table-column align="center" type="index" :index="getIndex" fixed="left" width="50"></el-table-column>

      <el-table-column align="center" :label="$t('用户名')" width="280" prop="username" fixed="left" sortable="custom">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.user.status==2" type="warning">{{ $t('用户注销') }}</el-tag>
          {{ maskStr(scope.row.user.username) }}
        </template>
      </el-table-column>

      <el-table-column width="160px" align="center" :label="$t('用户姓名')" prop="nickname">
        <template slot-scope="scope">
          {{ maskStr(scope.row.user.nickname) }}
        </template>
      </el-table-column>

      <el-table-column width="120px" align="center"  property="avatar" :label="$t('头像')">
        <template slot-scope="scope">
          <el-image preview-src-list style="border-radius:15%;width:50px" :src="scope.row.user.avatar"  width="20" lazy>
            <div slot="error" class="image-slot">
              <i style="font-size: 30px" class="el-icon-picture-outline-round"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" width="150px" :label="$t('头像')" prop="avatar" sortable/> -->

      <el-table-column align="center" :label="$t('性别')" prop="gender">
        <template slot-scope="scope">
          <span v-if="scope.row.user.gender == 0">{{ $t('其他') }}</span>
          <span v-if="scope.row.user.gender == 1">{{ $t('男') }}</span>
          <span v-if="scope.row.user.gender == 2">{{ $t('女') }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" width="150px" :label="$t('生日')" prop="birthday" sortable>
        <template slot-scope="scope">
          {{ maskStr(scope.row.user.birthday) }}
        </template>
      </el-table-column>

      <el-table-column width="150px" align="center" :label="$t('手机号码')" prop="mobile" >
        <template slot="header" slot-scope="{row}">
          {{ $t('手机号码') }}
          <i class="el-icon-mobile-phone" style="color: #de700c"></i>
        </template>
        <template slot-scope="scope">
          {{ maskStr(scope.row.user.mobile) }}
        </template>
      </el-table-column>

      <el-table-column width="160px" align="center" :label="$t('邮箱')" prop="email">
        <template slot="header" slot-scope="{row}">
          {{ $t('邮箱') }}
          <i class="el-icon-message" style="color: #de700c"></i>
        </template>
        <template slot-scope="scope">
          <span v-if="scope.row.user.email">{{ scope.row.user.email }}</span>
          <span v-else></span> <!-- 如果邮箱字段为空，则显示空 -->
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" min-width="100px" :label="$t('Member_ID')" prop="address.userId"/> -->

      <el-table-column align="center" min-width="100px" :label="$t('收货人名称')" prop="address.name">
        <template slot-scope="scope">
          {{ scope.row.name  }}
        </template>
      </el-table-column>

      <el-table-column align="center" min-width="100px" :label="$t('Cellphone_number')" prop="address.tel">
        <template slot-scope="scope">
          {{ scope.row.tel  }}
        </template>
      </el-table-column>

      <el-table-column align="center" min-width="100px" :label="$t('国家')">
        <template slot="header" slot-scope="{row}">
          {{$t('国家')}}
          <i class="el-icon-place"></i>
        </template>
        <template slot-scope="scope">
          {{ scope.row.country }}
        </template>
      </el-table-column>

      <el-table-column align="center" min-width="100px" :label="$t('省份')">
        <template slot="header" slot-scope="{row}">
          {{$t('省份')}}
          <i class="el-icon-place"></i>
        </template>
        <template slot-scope="scope">
          {{ scope.row.province }}
        </template>
      </el-table-column>

      <el-table-column align="center" min-width="100px" :label="$t('城市')">
        <template slot="header" slot-scope="{row}">
          {{$t('城市')}}
          <i class="el-icon-place"></i>
        </template>
        <template slot-scope="scope">
          {{ scope.row.city }}
        </template>
      </el-table-column>

      <el-table-column align="center" min-width="300px" :label="$t('详细地址')" prop="address.addressDetail">
        <template slot="header" slot-scope="{row}">
          {{$t('详细地址')}}
          <i class="el-icon-location-information"></i>
        </template>
        <template slot-scope="scope">
          {{ scope.row.addressDetail  }}
        </template>
      </el-table-column>

      <el-table-column align="center" min-width="80px" :label="$t('默认')" prop="address.isDefault">
        <template slot-scope="scope">
          {{ scope.row.isDefault ? '是' : '否' }}
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

  </div>
</template>

<script>
import { listAddress,listOpenEvent } from '@/api/user'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { listCountryRegion, listSubRegion } from '@/api/region'

export default {
  name: 'UserAddress',
  components: { Pagination },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      countrys:[],
      props: {
        value:'id',
        label: 'nameEn',
        children: 'children',
        checkStrictly: true
      },
      listQuery: {
        // 当前页码，默认为 1
        page: 1,
        // 每页显示的条目数，默认为 20
        limit: 20,
        // 名称，用于查询特定名称的项目，默认为 undefined
        name: undefined,
        // 用户ID，用于查询特定用户的项目，默认为 undefined
        userId: undefined,
        // 区域ID，用于查询特定区域的项目，默认为 undefined
        regionIds: undefined,
        // 是否打开过滤器，默认为 false
        openFilter: false,
        // 排序字段，默认为 'add_time'
        sort: 'add_time',
        // 排序顺序，默认为 'desc'
        order: 'desc'
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    this.getCountrys()
  },
  methods: {
    getList() {
      this.listLoading = true
      let param = _.clone(this.listQuery);
      if(param.regionIds){
        param.regionId = this.listQuery.regionIds[this.listQuery.regionIds.length-1]
      }
      delete param.regionIds
      listAddress(param).then(response => {
        this.list = response.data.data.list
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['地址ID', '用户ID', '收获人', '手机号', '省', '市', '区', '地址', '是否默认']
        const filterVal = ['id', 'userId', 'name', 'tel', 'province', 'city', 'county', 'addressDetail', 'isDefault']
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '用户地址信息')
        this.downloadLoading = false
      })
    },
    getIndex(index) {
      return (index + 1) + (this.listQuery.page - 1) * this.listQuery.limit;
    },

    /**
     * 处理选项变更事件，根据选项的值获取子地区数据并更新到相应的父级地区对象中
     * @param {Array} val - 选项的值，包含地区ID路径
     */
    handleItemChange(val) {
      // 获取路径步数
      let step = val.length;
      // 构建查询参数
      let query = {
        id: val[val.length - 1],
        type: 1
      };
      // 调用接口获取子地区数据
      listSubRegion(query).then(response => {
        // 根据路径查找父级地区对象
        let result = this.findObject(this.countrys, val);
        // 遍历子地区数据
        response.data.data.list.forEach(child => {
          // 根据步数决定是否为子地区对象设置默认值
          if (step <= 1) {
            result.children.push(this._.defaults(child, { children: [] }));
          } else {
            result.children.push(child);
          }
        });
      });
    },

    /**
     * 在数组中根据指定的id路径查找对象
     * @param {Array} arr - 要查找的数组
     * @param {Array} ids - 要查找的id路径
     * @returns {Object|undefined} - 返回找到的对象，如果未找到则返回undefined
     */
    findObject(arr, ids) {
      // 遍历数组
      for (let i = 0; i <= arr.length - 1; i++) {
        let obj = arr[i];
        // 如果ids数组长度为1且当前对象的id与ids中的id相等，则返回当前对象
        if (ids.length == 1 && obj.id == ids[0]) {
          return obj;
        } else if (obj.id == ids[0]) {
          // 如果当前对象的id与ids中的id相等，则递归调用findObject查找子对象
          ids.shift();
          return this.findObject(obj.children, ids);
        }
      }
    },


    /**
     * 获取国家列表并设置到组件的数据中
     */
    getCountrys() {
      // 调用后端接口获取国家列表数据
      listCountryRegion().then(response => {
        // 对返回的数据进行处理，设置到组件的数据中
        this.countrys = response.data.data.list.map(function(country) {
          return _.defaults(country, { children: [] });
        });
      });
    },

    /**
     * 对字符串进行部分遮蔽处理
     * @param {string} str - 待处理的字符串
     * @returns {string} - 处理后的字符串，前5位和后4位保留，中间部分用****代替
     */
    maskStr(str) {
      if (str) {
        // 如果字符串不为空，则对其进行部分遮蔽处理
        return str.substr(0, 5) + '****' + str.substr(7, str.length);
      } else {
        // 如果字符串为空，则返回默认字符串
        return '----- -----';
      }
    },
    openEvent(){
      this.getList()
    },
  }
}
</script>
